/*
 * @Author: TJN tjn@246@126.com
 * @Date: 2024-06-21 15:37:10
 * @LastEditors: TJN tjn@246@126.com
 * @LastEditTime: 2024-06-25 15:56:33
 * @FilePath: \hdcms-nest\src\auth\auth.service.ts
 * @Description:
 *
 * Copyright (c) 2024 by ${git_name_email}, All Rights Reserved.
 */
import { BadGatewayException, Injectable } from '@nestjs/common';
import RegisterDto from './dto/reigster.dto';
import { PrismaService } from 'src/common/prisma.service';
import { hash } from 'argon2';
import LoginDto from './dto/login.dto';
import { validateFail } from 'src/helper';
import { JwtService } from '@nestjs/jwt';
import { User } from '@prisma/client';
import { verify } from 'argon2';

@Injectable()
export class AuthService {
  constructor(
    private prisma: PrismaService,
    private jwt: JwtService,
  ) {}

  async register(dto: RegisterDto) {
    const user = await this.prisma.user.create({
      data: {
        name: dto.name,
        password: await hash(dto.password),
      },
    });

    return this.token(user);
  }

  async login(dto: LoginDto) {
    const user = await this.prisma.user.findFirst({
      where: {
        OR: [{ name: dto.name }, { email: dto.name }, { mobile: dto.name }],
      },
    });

    if (!(await verify(user.password, dto.password))) {
      throw new BadGatewayException('密码输入错误');
    }

    if (!user) {
      validateFail('name', '账号不存在');
    }

    return this.token(user);
  }

  private async token(user: User) {
    return {
      token: this.jwt.sign({ id: user.id }),
    };
  }
}
